package cn.doctor.assistant.pad.ui.ziliao;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.doctor.assistant.pad.R;
import cn.doctor.assistant.pad.api.ziliao.InformatApi;
import cn.doctor.assistant.pad.base.ResultCallback;
import cn.doctor.assistant.pad.entity.Course;
import cn.doctor.assistant.pad.entity.CourseResBean;
import cn.doctor.assistant.pad.entity.Record;
import cn.doctor.assistant.pad.ui.UI;
import cn.doctor.assistant.pad.ui.UploadImageActivity;
import cn.doctor.assistant.pad.ui.common.ImageGridAdapter;

/**
 * Created by jiaolf on 2016/4/1.
 * 新增病程记录
 */
public class AddBingChengActivity extends UploadImageActivity implements UploadImageActivity.OnFileUploadListener {

    @InjectView(R.id.titlebar_left_title)
    TextView titlebarLeftTitle;
    @InjectView(R.id.titlebar_right_text)
    TextView titlebarRightText;
    @InjectView(R.id.icon)
    ImageView icon;
    @InjectView(R.id.text_name)
    TextView textName;
    @InjectView(R.id.edit_record_date)
    EditText editRecordDate;
    @InjectView(R.id.edit_record_note)
    EditText editRecordNote;
    @InjectView(R.id.gridview)
    GridView gridview;

    ImageGridAdapter mGridAdapter;
    // 本地图片的path
    List<String> files = new ArrayList<>(5);

    // key 本地图片路径，value 服务器端的url路径
    Map<String, String> imagesUrl = new HashMap<>();

    Record mRecord;
    boolean saved;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_bingcheng);
        ButterKnife.inject(this);
        setTitle("新增病程记录");
        setRightTitleBarText("保存");
        setOnFileUploadListener(this);
        mRecord = (Record) getIntent().getExtras().getSerializable("record");
        initialize();
    }

    void initialize() {
        textName.setText(mRecord.getName());

        mGridAdapter = new ImageGridAdapter(this, files);
        mGridAdapter.setGridView(gridview);
        gridview.setAdapter(mGridAdapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == files.size()) {
                    showSelectPictureDialog();
                } else {
                    UI.showBigImage(files.get(position));
                }
            }
        });

        gridview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                                           int position, long id) {
                if (position == files.size()) {
                    return true;
                }
                selectedPosition = position;
                return false;
            }
        });

        registerForContextMenu(gridview);
    }

    private int selectedPosition;

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(100, 1, 1, "删除");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getItemId() == 1) {
            String key = files.remove(selectedPosition);
            imagesUrl.remove(key);
            mGridAdapter.notifyDataSetChanged();
            return true;
        }
        return super.onContextItemSelected(item);
    }

    void save() {
        if (TextUtils.isEmpty(recordStr)) {
            showToast("请填写记录日期");
            editRecordDate.requestFocus();
            return;
        }

        String content = editRecordNote.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            showToast("请添加记录内容");
            editRecordNote.requestFocus();
            return;
        }

        final Course course = new Course();
        course.setRecord_id(mRecord.getId());
        course.setName(mRecord.getName());
        course.setDate(recordStr);
        course.setContent(content);
        List<CourseResBean> pics = new ArrayList<>();
        for (int i = 0; i < files.size(); i++) {
            CourseResBean c = new CourseResBean();
            c.setPicture(imagesUrl.get(files.get(i)));
            pics.add(c);
        }

        course.setPictures(pics);

        showProgress("正在保存...");
        InformatApi.addBingCheng(course, new ResultCallback<String>() {
            @Override
            public void onSuccess(String result) {
                stopProgress();
                showToast(result);
                setDone();

                Intent intent = new Intent();
                intent.putExtra("course", course);
                setResult(RESULT_OK, intent);
            }
        });
    }

    // 保存后，不可再编辑
    void setDone(){
        saved = true;
        titlebarRightText.setVisibility(View.GONE);
        editRecordNote.setEnabled(false);
        editRecordDate.setEnabled(false);
        mGridAdapter.setDone(true);
        mGridAdapter.notifyDataSetChanged();
        unregisterForContextMenu(gridview);
    }

    @OnClick({R.id.titlebar_left_title, R.id.titlebar_right_text, R.id.edit_record_date})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.titlebar_left_title:
                boolean isEdited = !imagesUrl.isEmpty() || editRecordNote.getText().toString().trim().length() > 0;
                if (isEdited && !saved) {
                    showConfirmDialog();
                } else {
                    back();
                }
                break;
            case R.id.titlebar_right_text:
                save();
                break;
            case R.id.edit_record_date:
                setRecordDate();
                break;
        }
    }

    String recordStr;
    String recordDate; // 格式 "Apr 1, 2016 3:01:24 PM"

    void setRecordDate() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int monthOfYear = calendar.get(Calendar.MONTH);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH) + 1;

        new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                recordStr = String.format("%s-%02d-%02d", year, monthOfYear + 1, dayOfMonth);
                editRecordDate.setText(recordStr);

                Date date = new Date();
                date.setYear(year - 1900);
                date.setMonth(monthOfYear);
                date.setDate(dayOfMonth);
                recordDate = String.format(Locale.US, "%tb %d, %d 00:00:00", date, dayOfMonth, year);
//                UI.showToast(recordDate);

            }

        }, year, monthOfYear, dayOfMonth).show();
    }

    void showSelectPictureDialog() {
        String[] items = {"拍照", "从手机中选择"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("上传图片").setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        selectPicFromCamera(0);
                        break;
                    case 1:
                        selectPicFromLocal(0);
                        break;
                }
            }
        }).setPositiveButton("取消", null);
        builder.show();
    }

    @Override
    public void onUploading(long total, long current, int tag) {

    }

    @Override
    public void onSuccess(String fileLocalPath, String fileURL, int tag) {
        //loadImage();
        files.add(fileLocalPath);// 本地图片，UI显示
        mGridAdapter.notifyDataSetChanged();
        imagesUrl.put(fileLocalPath, fileURL);
        UI.showToast("上传成功：" + fileURL);
    }

    @Override
    public void onFailure(String msg, int tag) {
        showToast(msg);
    }


    void showConfirmDialog() {

        new AlertDialog.Builder(this).setCancelable(false).setMessage("信息还未保存，是否保存？").setTitle("提示")
                .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt) {
                        // 保存
                        save();
                    }
                }).setNegativeButton("放弃", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                onBackPressed();
            }
        }).create().show();

    }

}
